// pages/chapterPractice/chapterPractice.js
const API_BASE       = 'https://tihaidengta.xyz';
const STORAGE_KEY    = 'chapter_practice_progress';
const FAVORITE_KEY   = 'favoriteQuestions';
const WRONG_KEY      = 'wrongQuestions';

function saveWrongQuestion(q) {
  const list = wx.getStorageSync(WRONG_KEY) || [];
  if (!list.find(item => item.uniqId === q.uniqId)) {
    list.push({
      uniqId: q.uniqId,
      content: q.content,
      subjectType: q.subjectType,
      optionsArray: q.optionsArray || [],
      answer: q.answer,
      explanation: q.explanation || ''
    });
    wx.setStorageSync(WRONG_KEY, list);
  }
}

Page({
  data: {
    isDarkMode: false,
    showThemePanel: false,
    bankId: '',
    questions: [],
    currentIndex: 0,
    userAnswer: '',
    answeredQuestions: [],
    showResult: false,
    correctCount: 0,
    userAnswers: {}, // ✅ 新增答题记录对象
    isLoading: false,
    slideTransform: '',
    startTouchX: 0,
    endTouchX: 0
  },

  onLoad(options) {
    const isDark = wx.getStorageSync('isDarkMode') || false;
    this.setData({ isDarkMode: isDark });
    const { bankId } = options;
    this.setData({ bankId });
    const cache = wx.getStorageSync(STORAGE_KEY);
    if (cache && Array.isArray(cache.questions)) {
      wx.showModal({
        title: '检测到未完成练习',
        content: '是否继续上次练习？',
        confirmText: '继续',
        cancelText: '重做',
        success: res => {
          if (res.confirm) {
            this.setData(cache);
            return;
          }
          this.clearCache();
          this.fetchQuestions();
        }
      });
    } else {
      this.fetchQuestions();
    }
  },

  fetchQuestions() {
    if (this.data.isLoading) return;
    this.setData({ isLoading: true });
    wx.showLoading({ title: '加载题目...', mask: true });
    const token = wx.getStorageSync('token');
    const favs = wx.getStorageSync(FAVORITE_KEY) || [];
    wx.request({
      url: `${API_BASE}/eduservice/subject/randomQuestions2`,
      method: 'GET',
      header: { token: token },
      success: res => {
        const raw = res.data.data?.list || [];
        const questions = raw.map((item, i) => {
          const opts = [];
          if (item.subjectType === 1) {
            ['a','b','c','d'].forEach((k, idx) => {
              if (item[k]) opts.push({
                key: String.fromCharCode(65 + idx),
                text: item[k],
                statusClass: ''
              });
            });
          }
          const collected = favs.some(f => f.uniqId === item.uniqId);
          return {
            uniqId: item.uniqId || i,
            content: item.title,
            subjectType: item.subjectType,
            answer: item.answer,
            explanation: item.subjectNote || '',
            optionsArray: opts,
            userAnswer: '',
            collected
          };
        });
        this.setData({
          questions,
          currentIndex: 0,
          userAnswer: '',
          answeredQuestions: [],
          showResult: false,
          correctCount: 0,
          userAnswers: {} // ✅ 初始化 userAnswers
        });
      },
      fail: () => wx.showToast({ title: '题目加载失败', icon: 'none' }),
      complete: () => {
        wx.hideLoading();
        this.setData({ isLoading: false });
      }
    });
  },

  toggleCollect() {
    const idx = this.data.currentIndex;
    const qs  = this.data.questions;
    const q   = qs[idx];
    q.collected = !q.collected;
    qs[idx] = q;
    this.setData({ questions: qs });
    let favs = wx.getStorageSync(FAVORITE_KEY) || [];
    if (q.collected) {
      favs.push(q);
      wx.showToast({ title: '已加入收藏', icon: 'none' });
    } else {
      favs = favs.filter(x => x.uniqId !== q.uniqId);
      wx.showToast({ title: '已取消收藏', icon: 'none' });
    }
    wx.setStorageSync(FAVORITE_KEY, favs);
  },

  onSelect(e) {
    const uniqId = e.currentTarget.dataset.uniqid;
    const key    = e.currentTarget.dataset.key;
    const idx    = this.data.questions.findIndex(q => q.uniqId === uniqId);
    if (idx < 0) return;
    const q = this.data.questions[idx];
    if (q.userAnswer) return;

    const ua = this.data.userAnswers;
    ua[idx] = key; // ✅ 记录选择题答案

    q.userAnswer = key;
    q.optionsArray = q.optionsArray.map(opt => {
      let cls = '';
      if (opt.key === q.answer) cls = 'correct';
      else if (opt.key === key) cls = 'wrong';
      return { ...opt, statusClass: cls };
    });

    const correct = key === q.answer;
    if (!correct) {
      saveWrongQuestion(q);
    } else {
      this.setData({ correctCount: this.data.correctCount + 1 });
    }

    const ans = [...new Set([...this.data.answeredQuestions, idx])];
    this.setData({
      questions: this.data.questions,
      showResult: true,
      answeredQuestions: ans,
      userAnswers: ua
    });

    this.saveProgress();
    if (correct) setTimeout(() => this.nextQuestion(), 800);
  },

  onInputAnswer(e) {
    this.setData({ userAnswer: e.detail.value });
  },

  submitTextAnswer() {
    const idx = this.data.currentIndex;
    const q   = this.data.questions[idx];
    if (q.userAnswer) return;

    const val = this.data.userAnswer.trim();
    q.userAnswer = val;
    const correct = val === (q.answer || '').trim();

    const ua = this.data.userAnswers;
    ua[idx] = val; // ✅ 记录文本题答案

    if (!correct) {
      saveWrongQuestion(q);
    } else {
      this.setData({ correctCount: this.data.correctCount + 1 });
    }

    const ans = [...new Set([...this.data.answeredQuestions, idx])];
    this.setData({
      questions: this.data.questions,
      showResult: true,
      answeredQuestions: ans,
      userAnswers: ua
    });

    this.saveProgress();
    if (correct) setTimeout(() => this.nextQuestion(), 800);
  },

  changeQuestion(e) {
    const idx = e.detail.index;
    this.setData({
      currentIndex: idx,
      showResult: false,
      userAnswer: ''
    });
  },

  prevQuestion() {
    if (this.data.currentIndex > 0) {
      const ni = this.data.currentIndex - 1;
      this.setData({
        currentIndex: ni,
        userAnswer: this.data.questions[ni].userAnswer,
        showResult: false
      });
    }
  },

  nextQuestion() {
    const ni = this.data.currentIndex + 1;
    if (ni < this.data.questions.length) {
      this.setData({
        currentIndex: ni,
        userAnswer: this.data.questions[ni].userAnswer,
        showResult: false
      });
    } else {
      this.finishPractice();
    }
  },

  finishPractice() {
    this.clearCache();
    wx.showModal({
      title: '练习完成',
      content: `共 ${this.data.questions.length} 题，答对 ${this.data.correctCount} 题`,
      showCancel: false,
      success: () => wx.navigateBack()
    });
  },

  saveProgress() {
    const { questions, currentIndex, correctCount, answeredQuestions, userAnswers } = this.data;
    wx.setStorageSync(STORAGE_KEY, { questions, currentIndex, correctCount, answeredQuestions, userAnswers });
  },

  clearCache() {
    wx.removeStorageSync(STORAGE_KEY);
  },

  touchStart(e) {
    this.setData({ startTouchX: e.changedTouches[0].pageX });
  },
  touchMove(e) {
    const moveX = e.changedTouches[0].pageX - this.data.startTouchX;
    const max   = 100;
    const limit = Math.min(Math.max(moveX, -max), max);
    this.setData({ slideTransform: `translateX(${limit}px)` });
  },
  touchEnd(e) {
    this.setData({ endTouchX: e.changedTouches[0].pageX });
    const { startTouchX, endTouchX } = this.data;
    if (endTouchX - startTouchX > 50) this.prevQuestion();
    else if (startTouchX - endTouchX > 50) this.nextQuestion();
  },

  toggleThemePanel() {
    this.setData({ showThemePanel: !this.data.showThemePanel });
  },
  toggleDarkMode(e) {
    const isDark = e.detail.value;
    wx.setStorageSync('isDarkMode', isDark);
    this.setData({ isDarkMode: isDark });
  }
});
